﻿using System.Windows;
using System.Windows.Controls;

namespace Calculator
{
    public partial class LenthConvert : UserControl
    {
        public LenthConvert()
        {
            InitializeComponent();

            // 设置默认选择
            InputUnitComboBox.SelectedIndex = 0;
            ResultUnitComboBox.SelectedIndex = 0;
        }

        // 转换按钮点击事件
        private void ConvertButton_Click(object sender, RoutedEventArgs e)
        {
            // 获取输入的数值
            if (!double.TryParse(InputTextBox.Text, out double inputValue))
            {
                MessageBox.Show("请输入有效的数值", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 获取单位
            string inputUnit = (InputUnitComboBox.SelectedItem as ComboBoxItem)?.Content.ToString();
            string resultUnit = (ResultUnitComboBox.SelectedItem as ComboBoxItem)?.Content.ToString();

            // 验证单位选择
            if (string.IsNullOrEmpty(inputUnit) || string.IsNullOrEmpty(resultUnit))
            {
                MessageBox.Show("请选择有效的单位", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 转换逻辑
            double valueInMeters = ConvertToMeters(inputValue, inputUnit);
            double resultValue = ConvertFromMeters(valueInMeters, resultUnit);

            // 显示结果
            ResultTextBox.Text = resultValue.ToString("F2");
        }

        // 将输入值转换为米
        private double ConvertToMeters(double value, string unit)
        {
            return unit switch
            {
                "米" => value,
                "千米" => value * 1000,
                "厘米" => value / 100,
                "毫米" => value / 1000,
                "英里" => value * 1609.34,
                "英尺" => value * 0.3048,
                _ => value
            };
        }

        // 将米转换为目标单位
        private double ConvertFromMeters(double value, string unit)
        {
            return unit switch
            {
                "米" => value,
                "千米" => value / 1000,
                "厘米" => value * 100,
                "毫米" => value * 1000,
                "英里" => value / 1609.34,
                "英尺" => value / 0.3048,
                _ => value
            };
        }
    }
}
